/* 火车站点维护 */
<template> 
    <div>
        <condition-card @reset="resetSearch" @search="onSearch" label-position="right" label-width="170px">
            <el-row :gutter="24" style="height: 50px;">
                <!-- 省份 -->
                <el-col :span="8">
                    <el-form-item :label="$t('trainStation.province')">
                        <el-select v-model="queryForm.proviceCode" clearable style="width:100%">
                            <el-option
                                v-for="item in options.proviceList"
                                :key="item.keyValue"
                                :label="item.showValue"
                                :value="item.keyValue">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <!-- 站点名称 -->
                <el-col :span="8">
                    <el-form-item :label="$t('trainStation.stationName')">
                        <el-input v-model="queryForm.station" maxlength="12" clearable :placeholder="$t('trainStation.pleaseEnter')"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </condition-card>

        <el-card shadow="never" v-loading="loading" body-style="padding: 24px;" class="card-margin">
            <h1 class="condition-title">{{ $t('trainStation.trainStationList') }}</h1>
            <el-row style="padding:10px;" class="row-bg" justify="space-between">
                <div>
                    <el-button type="primary" style="float:right; margin-left:10px;" @click="add()">{{ $t('trainStation.add') }}</el-button><!-- 新增 -->
                    <el-dropdown placement='bottom-start' trigger="click" @command="downloadFile" style="float:right; margin-left:10px;">
                        <el-button type="primary">{{ $t('trainStation.import') }}<i class="el-icon-arrow-down el-icon--right"></i></el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="importData">{{ $t('trainStation.importData') }}</el-dropdown-item><!-- 导入 -->
                            <el-dropdown-item command="download">{{ $t('trainStation.downLoadData') }}</el-dropdown-item><!-- 下载模板 -->
                        </el-dropdown-menu>
                    </el-dropdown>
                </div>
            </el-row>
            <edu-table :pagination="false" :selection='false' :order="true" :tooltipEffect="tooltipEffect" stripe :data="dataList" size="mini">
                <edu-table-column align='center' :label="$t('trainStation.province')" prop="provice"></edu-table-column> <!-- 省份 -->
                <edu-table-column align='center' :label="$t('trainStation.stationName')" prop="station"></edu-table-column> <!-- 站点名称 -->
                <!-- 操作 -->
                <edu-table-column align='center' :label="$t('trainStation.operation')">
                    <template slot-scope="scope">
                        <el-button type="text" @click="edits(scope.row)">{{ $t('trainStation.edit') }}</el-button>
                    </template>
                </edu-table-column>
            </edu-table>
            <el-row type="flex" class="row-bg" justify="end">
                <el-col>
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="queryForm.pageNum_"
                        :page-sizes="[10, 20, 30, 40]"
                        :page-size="queryForm.pageSize_"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total_"
                        style="float:right;margin-top:10px"></el-pagination>
                </el-col>
            </el-row>
        </el-card>

        <el-dialog :before-close="cancel" :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
            <el-form :model="form" :rules="rules" ref="refForm" label-suffix="：" label-position="right" label-width="100px">
                <el-row>
                    <el-col :span="10">
                        <el-form-item :label="$t('trainStation.province')" prop="provice">
                            <el-select v-model="form.provice" @change="changeProvice" clearable style="width:100%">
                                <el-option
                                    v-for="item in options.proviceList"
                                    :key="item.keyValue"
                                    :label="item.showValue"
                                    :value="item.keyValue">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item :label="$t('trainStation.stationName')" prop="station">
                            <el-input v-model="form.station" maxlength="12" clearable :placeholder="$t('trainStation.pleaseEnter')"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">{{ $t('trainStation.cancel') }}</el-button>
                <el-button type="primary" @click="determine('refForm')">{{ $t('trainStation.determine') }}</el-button>
            </div>
        </el-dialog>


        <edu-dialog
            :title="$t('trainStation.importData')"
            width="600px"
            ref="uploadDialog"
            @close="clearFiles"
            @confirm="uploadFile"
        >
            <div style="height:100px">
                <el-form label-width="85px">
                    <el-form-item>
                        <el-upload
                            ref="upload"
                            :data="{}"
                            :on-success="uploadDone"
                            :on-error="onError"
                            :auto-upload="false"
                            :multiple="false"
                            :on-change="(file, fileList)=>{this.fileList = fileList}"
                            :limit="1"
                            accept=".xlsx"
                            action="api/studentservice/station/importStation"
                            :before-upload="beforeAvatarUpload"
                        >
                            <el-button
                                slot="trigger"
                                size="small"
                                type="primary"
                            >{{$t('label.selectFile')}}</el-button>
                            <div slot="tip" class="el-upload__tip">{{ $t('trainStation.onlyImportFile') }}</div>
                        </el-upload>
                    </el-form-item>
                </el-form>
            </div>
        </edu-dialog>

        <el-dialog :title="$t('trainStation.tips')" :visible.sync="dialogTableVisible" width="30%">
            <el-table height="250" style="width:100%" stripe :data="errList" size="mini" v-show="ifErr" tooltip-effect="light">
                <!-- 未成功导入数据原因 -->
                    <el-table-column
                        :label="$t('trainStation.cantNotImportReason')"
                        prop="msg"
                        show-overflow-tooltip
                    >
                    </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>
<script>
import { queryDic } from 'common/src/api/dictionary'
import UTILS from 'common/src/utils/utils'
import { listStation , selectStation, editStation, downloadTemplates, importStation, getStuAppoint } from 'common/src/api/studentinfo'
export default {
    components: {
   
    },
    data() {
        return {
            dialogTableVisible: false,
            errList: [],
            ifErr: false, // 是否展示错误信息
            importTime: null, //轮询导入
            importKey: '', // 导入获取的key
            fileList: [],
            title: this.$t('trainStation.add'),
            dialogFormVisible: false,
            dataList: [],
            total_: 0,
            queryForm: {
                pageNum_: 1,
                pageSize_: 10,
                proviceCode: '', // 省份code
                station: '' // 站点
            },
            options: {
                proviceList: []
            },
            form: {
                id: '',
                proviceCode: '', // 省份code
                station: '', // 站点
                provice: ''
            },
            rules: {
                provice: [
                    { required: true, message: this.$t('trainStation.plzProvince'), trigger: 'change' }
                ],
                station: [
                    { required: true, message: this.$t('trainStation.plzStationName'), trigger: 'blur' }
                ]
            }
        }
    },
    created() {

    },
    mounted() {
        this.getStationList()
        this.getProviceList()
    },
    methods: {
        clearFiles() {
            this.$refs.upload.clearFiles();
            this.fileList = [];
        },
        // 提交
        uploadFile() {
            if (this.fileList.length == 0) {
                this.$message({
                    type: "warning",
                    // message: "请选择要上传的文件"
                    message: this.$t('trainStation.pzlUploadFile')
                });
                return;
            }
            this.$refs.upload.submit()
        },
        // 成功回调
        uploadDone(res, file, fileList) {
            this.errList = []
            if(res.code === 200) {
                this.importKey = res.data
                this.$refs.uploadDialog.close();
                // this.$message.success(this.$t('newInfoImport.exportok'));
            } else if (res.code === 300 && res.msg){
                this.$message({
                    type: 'error',
                    message: res.msg
                })
                this.$refs.uploadDialog.close()
                return;
            }
            if (res.data) {
                this.importTime = setInterval(() => {
                    getStuAppoint(this.importKey).then(resT => {
                        if (resT.code === 200) {
                            if (resT.data && resT.data.status) {
                                clearInterval(this.importTime);
                                if (resT.success === false) {
                                    this.$message.error(this.$t('trainStation.uploadError')) // 上传失败
                                } else {
                                    if (resT.data && resT.data.msg) {
                                        this.dialogTableVisible = true
                                        let msgList = resT.data.msg.split(';')
                                        if (msgList && msgList.length > 0) {
                                            msgList.forEach(val=> {
                                                this.errList.push(
                                                    {
                                                        msg:val
                                                    }
                                                )
                                            })
                                        }
                                    } else {
                                        this.$message.success(this.$t('newInfoImport.exportok'));
                                    } 
                                } 
                            }
                        } else throw res.code;
                    });
                }, 3000)
                this.ifErr = true
            }
        },
        onError(err, file, fileList) {
            let msg = JSON.parse(err.message);
            this.$message({
                type: "error",
                message: msg.message
            });
        },
        beforeAvatarUpload(file) {
            const isLt2M = file.size / 1024 / 1024 < 10;
            if (!isLt2M) {
                // this.$message.error("上传文件大小不能超过 10MB!");
                this.$message.error(this.$t('trainStation.cantNotBeyond'));
                this.clearFiles();
                return false;
            }
            const types = [
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            ];
            if (!types.includes(file.type)) {
                // this.$message.error("上传文件格式必须是.xlsx");
                this.$message.error(this.$t('trainStation.uploadFiles'));
                this.clearFiles();
                return false;
            }
        },
        // 改变弹框内的省份
        changeProvice(val) {
            this.options.proviceList.forEach(ele => {
                if (val === ele.keyValue) {
                    this.form.proviceCode = ele.keyValue
                    this.form.provice = ele.showValue
                }
            })
        },
        // 火车站点列表
        getStationList() {
            listStation(this.queryForm).then(res => {
                if (res.code === 200) {
                    this.dataList = res.data.list
                    this.total_ = res.data.total_ 
                }
            })
        },
        // 省份下拉框
        getProviceList() {
            selectStation().then(res => {
                let proviceList = []
                proviceList = res.data
                this.options.proviceList = proviceList
            })
        },
        // 重置
        resetSearch() {
            this.queryForm.proviceCode = ''
            this.queryForm.station = ''
            this.queryForm.pageNum_ = 1
            this.getStationList()
        },
        // 筛选
        onSearch() {
            this.queryForm.pageNum_ = 1
            this.getStationList()
        },
        // 批量导入
        downloadFile(command) {
            // 导入
            if (command === 'importData') {
                this.$refs.uploadDialog.open();
            } 
            // 下载模板
            else if (command === 'download') {
                downloadTemplates().then(res => {
                    this.$message.success(this.$t('internship.successfully'))   
                })
            }
        },
        // 新增
        add() {
            this.form.id = ''
            this.form.proviceCode = ''
            this.form.station = ''
            this.form.provice = ''
            this.dialogFormVisible = true
            this.title = this.$t('trainStation.add')
        },
        // 编辑
        edits(data) {
            this.dialogFormVisible = true
            this.title = this.$t('trainStation.edit')
            this.form.provice = data.provice
            this.form.proviceCode = data.proviceCode
            this.form.station = data.station
            this.form.id = data.id
        },
        // 处理分页大小
        handleSizeChange(val) {
            this.queryForm.pageSize_ = val
            this.queryForm.pageNum_ = 1
            this.getStationList()
        },
        // 处理分页改变
        handleCurrentChange(val) {
            this.queryForm.pageNum_ = val
            this.getStationList()
        },
        // 弹框内取消
        cancel() {
            this.dialogFormVisible = false
            this.$refs['refForm'].resetFields()
            for (let key in this.form) {
                this.form[key] = ''
            }
        },
        // 弹框内确定
        determine(refForm) {
            this.$refs[refForm].validate((valid) => {
                if (valid) {
                    if (this.title === this.$t('trainStation.add')) {
                        let obj = {
                            proviceCode: this.form.proviceCode,
                            station: this.form.station,
                            provice: this.form.provice
                        }
                        editStation(obj).then((res) => {
                            this.dialogFormVisible = false
                            this.$message({ type: 'success', message: this.$t('internship.successfully') })
                            this.$refs['refForm'].resetFields()
                            for (let key in this.form) {
                                this.form[key] = ''
                            }
                            this.queryForm.pageNum_ = 1 
                            this.getStationList()
                        })
                    } else {
                        editStation(this.form).then((res) => {
                            this.dialogFormVisible = false
                            this.$message({ type: 'success', message: this.$t('internship.successfully') })
                            this.$refs['refForm'].resetFields()
                            for (let key in this.form) {
                                this.form[key] = ''
                            }
                            this.queryForm.pageNum_ = 1 
                            this.getStationList()
                        })
                    }
                }
            })
        }
    }
}
</script>
<style scoped>

</style>
